#include"mystdio.h"
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>

MYFILE *mfopen(const char *filename,const char *mode)
{
    int fd = -1;
    if(strcmp(mode,"r") == 0)
    {
        fd = open(filename,O_RDONLY);
    }
    else if(strcmp(mode,"w") == 0)
    {
        fd = open(filename,O_CREAT | O_WRONLY | O_TRUNC,0666);
    }
    else if(strcmp(mode,"a") == 0)
    {
        fd = open(filename,O_CREAT | O_WRONLY | O_APPEND,0666);
    }

    if(fd < 0) return NULL;

    MYFILE*myfile = (MYFILE*)malloc(sizeof(MYFILE));
    if(!myfile)
    {
        close(fd);
        return NULL;
    }

    myfile->flag = FLUSH_LINE;
    myfile->fileno = fd;
    myfile->cap = SIZE;
    myfile->size = 0;
    return myfile;

}

void mfflush(MYFILE*stream)
{
    if(stream->size > 0)
    {
        //调用系统调用，将内容写入系统级缓冲区中
        write(stream->fileno,stream->outbuffer,stream->size);
        stream->size = 0;
    }
}

int mfwrite(const void *ptr,int num,MYFILE*stream)
{
    //1.拷贝
    memcpy(stream->outbuffer,ptr,num);
    stream->size += num;
    //2.刷新
     if(stream->flag == FLUSH_LINE && stream->size > 0 && stream->outbuffer[stream->size-1]== '\n')
    {
        mfflush(stream);
    }
    return stream->size <= stream->cap ? num : num - stream->cap;
}
void mfclose(MYFILE*stream)
{
    if(stream->size > 0)
    {
        mfflush(stream);
    }
    close(stream->fileno);
}
